package com.yzj.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
@Component
public class AuthorFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 2;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext ctx=RequestContext.getCurrentContext();
        System.out.println("AuthorityFilter shouldFilter:"+ctx.sendZuulResponse());
        return ctx.sendZuulResponse();
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext ctx=RequestContext.getCurrentContext();
        HttpServletRequest request=ctx.getRequest();
        String token=request.getHeader("token");
        System.out.println("AuthorityFilter run："+token);
        if (token==null||token.isEmpty()){
            System.out.println("Token为空，不能继续请求服务。。。");
            ctx.setResponseStatusCode(401);
            ctx.setSendZuulResponse(false);
            ctx.getResponse().setContentType("text/html;charset=utf-8");
            ctx.setResponseBody("{\"msg\":\"Token为空，不允许访问服务！\"}");
        }else {
            System.out.println("Token合法，继续传递请求到服务。。。");
            ctx.setSendZuulResponse(true);
        }
        return null;
    }
}
